import Vue from 'vue'
import Vuex from 'vuex'
import { dealColorSize, isInvalid } from '@/unit'
import { Message } from 'element-ui'
import $http from '@/request'
import pro from '@/assets/img/default.png'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    area: '',//地区
    user: '',//门店
    userCode: '',//门店code
    distribId: '',//配销中心id
    distribCode: '',//配销中心编码
    userId: 200000243752,//门店id
    recommendHomeData: [], // 首页数据
    sortHomeList: [
      {
        des: true, // 默认降序
        name: 'tagId'
      },
      {
        des: false, // 默认升序
        name: 'styClearId'
      },
      /*{
        des: true, // 默认降序
        name: 'sporadicCode'
      },*/
      {
        des: true, // 默认降序
        name: 'retailAmt7d'
      },
      {
        des: false, // 默认升序
        name: 'styId'
      }
    ],// 首页默认排序方式
    selectSortList: [],//选择后的排序
    detailsLocation: 0,//缓存配置详情页的滚动位置
    recordRoute: [
      {
        path: '/recommend',
        label: '选款推荐'
      }
    ],//记录的路由列表
    static: pro,//默认图片
    evaluationDetail: null,//在商品详情界面已评价后
    reservationDetail: null,//在商品详情界面已预定或取消预定后
    collectionDetail: null,//在商品详情界面已收藏或取消后
  },
  mutations: {
    /*提示错误信息*/
    dialogErr (state, data) {
      !data.noMessage && Message.error(`${data.message}`);
    },
    /*记录路由信息*/
    setRecordRoute (state, data) {
      if(data.path === '/recommend') return state.recordRoute = [{
        path: '/recommend',
        label: '选款推荐'
      }];
      !state.recordRoute.find(n => {
        let path = data.path.split('?')[0];
        return n.path.includes(path);
      }) && state.recordRoute.push({ ...data });
    },
    /*删除记录*/
    delRecordRoute (state) {
      state.recordRoute.pop();
    },
    /*缓存配置详情页的滚动位置*/
    recordLocation (state, data) {
      state.detailsLocation = data;
    },
    /*动态获取门店id*/
    dynamicSetUerId (state, data) {
      state.userId = Number(data);
    },
    /*设置用户信息*/
    serUserInform (state, data) {
      state.area = data.distribName;
      state.user = data.strName;
      state.userCode = data.strCode;
      state.distribId = data.distribId;
      state.distribCode = data.distribCode;
    },
    /*保存已评价商品的信息*/
    saveEvaluation (state, data) {
      state.evaluationDetail = data;
    },
    /*保存已预定的商品信息*/
    saveReservation (state, data) {
      state.reservationDetail = data;
    },
    /*保存已收藏的商品信息*/
    saveCollection (state, data) {
      state.collectionDetail = data;
    },
    /* 设置首页数据 */
    setHomeRecommendData (state, data) {
      state.recommendHomeData = data;
    },



    /* 修改首页的收藏 */
    homeCollect (state, { classId, sexId, pro, id, displayId, target, status }) {
      let index, i;
      index = state.recommendHomeData.findIndex(obj => {
        if(obj.classId === classId && obj.sexId === sexId && obj.displayId === displayId) {
          i = obj[target].arr.findIndex(n => n.pro === pro && n.styId === id);
          return true;
        }else return false
      })
      if(index === -1 || i === -1) return;
      state.recommendHomeData[index][target].arr[i].collect = !status;
    },
    /* 删除首页的可选款 */
    deleteHomeDetail (state, { classId, sexId, pro, displayId, id, target }) {
      let index, i;
      index = state.recommendHomeData.findIndex(obj => {
        if(obj.classId === classId && obj.sexId === sexId && obj.displayId === displayId) {
          i = obj[target].arr.findIndex(n => n.pro === pro && n.styId === id);
          return true;
        }else return false
      })
      if(index === -1 || i === -1) return;
      state.recommendHomeData[index][target].arr.splice(i, 1);
      this.commit('fnProcess', { index })
    },
    /* 处理右边勾选联动 */
    fnProcess (state, { index }) {
      let item = state.recommendHomeData[index];
      // 左边已勾选数(退仓款并且现有款标识为1)
      let checkedCount = item.leftLists.arr.filter(n => n.isReturnWarehouse && n.currentId == 1 && n.checked).length;
      // 右边已勾选数量(不包含清理款)
      let nowChecked = item.rightLists.arr.filter(n => !n.disabled && !n.isClear && n.checked).sort((a, b) => b.chooseDate - a.chooseDate);
      // 右边可勾选数量
      let choosable = item.realChoose + checkedCount;
      // 修改可补充款数显示值
      item.choosable = choosable >= 0? choosable : 0;
      // 可选款小于0直接将非清理款的全部禁用
      if(choosable <= 0) {
        state.recommendHomeData[index].rightLists.arr = state.recommendHomeData[index].rightLists.arr.map(n => ({
          ...n,
          disabled: !n.isClear? true : n.disabled,
          checked: !n.isClear? false : n.checked
        }))
      }else { // 可选款大于0
        // 获取现右边已勾选款 - 可选款数的差值
        let differenceVal = nowChecked.length - item.choosable;
        // 差值大于0将多余的勾选去掉并禁用
        if(differenceVal >= 0) {
          let arr = nowChecked.splice(0, differenceVal).map(n => n.styId);
          state.recommendHomeData[index].rightLists.arr = state.recommendHomeData[index].rightLists.arr.map(n => {
            if(!n.isClear && (arr.includes(n.styId) || !n.checked)) {
              return {
                ...n,
                disabled: true,
                checked: false
              }
            } else return n
          })
        }else {
          // 全部打开
          state.recommendHomeData[index].rightLists.arr = state.recommendHomeData[index].rightLists.arr.map(n => ({
            ...n,
            disabled: false
          }))
        }
      }
      // 判断右边大类是否禁用
      let rightCanChoose = item.rightLists.arr.filter(n => !n.disabled).length;
      // 右边已勾选总数
      let rightNowChecked = item.rightLists.arr.filter(n => !n.disabled && n.checked).length;
      // 当没有可勾选项时,禁用大类勾选
      item.rightLists.disabled = rightCanChoose === 0;
      item.rightLists.checked = rightCanChoose === 0? false : rightNowChecked === rightCanChoose;
    },
    /* 首页的选择框 */
    changeHomeCheck (state, { type, classId, sexId, pro, displayId, id, target, status }) {
      let index, i;
      index = state.recommendHomeData.findIndex(obj => {
        if(obj.classId === classId && obj.sexId === sexId && obj.displayId === displayId) {
          if(type === 'single') {
            i = obj[target].arr.findIndex(n => n.pro === pro && n.styId === id);
          }
          return true;
        }else return false
      })
      if(index === -1) return;
      let targetObj = state.recommendHomeData[index][target];
      if(targetObj.disabled) return;
      if(target === 'leftLists') {
        // 勾选单个
        if(type === 'single' && i !== -1) {
          targetObj.arr[i].checked = !status;
          // 可勾选总数
          let total = targetObj.arr.filter(n => !n.disabled).length;
          // 已勾选总数
          let nowChecked = targetObj.arr.filter(n => !n.disabled && n.checked).length;
          // 大类是否勾选
          targetObj.checked = total === nowChecked;
        }
        // 勾选大类
        if(type === 'class') {
          targetObj.checked = !status;
          targetObj.arr = targetObj.arr.map(obj => {
            return Object.assign({}, obj, {
              checked: !obj.disabled? !status : false
            })
          })
        }
      }else {
        if(type === 'single' && i !== -1) {
          targetObj.arr[i].checked = !status;
          targetObj.arr[i].chooseDate = new Date().getTime(); // 勾选过的标识符
        }
        if(type === 'class') {
          targetObj.checked = !status;
          let dateTime = new Date().getTime();
          targetObj.arr = targetObj.arr.map(obj => ({
            ...obj,
            checked: targetObj.checked,
            chooseDate: dateTime + obj.sortId,
            disabled: false
          }))
        }
      }
      // 联动处理右边的
      this.commit('fnProcess', { index })
    },
    /* 首页全选 */
    changeHomeAllCheck (state, checked) {
      state.recommendHomeData.map((obj, index) => {
        state.recommendHomeData[index].leftLists = {
          checked: !obj.leftLists.disabled? !checked : false,
          disabled: obj.leftLists.disabled,
          arr: obj.leftLists.arr.map(n => ({
            ...n,
            checked: !obj.disabled? !checked : false
          }))
        }
        this.commit('changeHomeCheck', {
          type: 'class',
          sexId: obj.sexId,
          classId: obj.classId,
          displayId: obj.displayId,
          status: checked,
          target: 'rightLists'
        })
      })
    },
    /* 减少或增加首页数量 */
    addOrSubtractOfHome (state, { style, classId, sexId, pro, displayId, id, k, j, count, target }) {
      let index, i;
      index = state.recommendHomeData.findIndex(obj => {
        if(obj.classId === classId && obj.sexId === sexId && obj.displayId === displayId) {
          i = obj[target].arr.findIndex(n => n.pro === pro && n.styId === id);
          return true;
        }else return false
      })
      if(index === -1 || i === -1) return;
      Vue.set(state.recommendHomeData[index][target].arr[i].skuData.data[k].count[j], 'new', style === 'add'? count + 1 : count - 1);
    },
    /* 恢复首页未修改前的sku数量 */
    refreshHomeSkuCount (state, { classId, sexId, pro, displayId, id, target }) {
      let index, i;
      index = state.recommendHomeData.findIndex(obj => {
        if(obj.classId === classId && obj.sexId === sexId && obj.displayId === displayId) {
          i = obj[target].arr.findIndex(n => n.pro === pro && n.styId === id);
          return true;
        }else return false
      })
      if(index === -1 || i === -1) return;
      state.recommendHomeData[index][target].arr[i].skuData.data.forEach(obj => {
        obj.count.forEach(count => {
          count.new = count.old;
        })
      })
    },
    /* 修改首页可选款数量 */
    modifyHomeCommodityCount (state, { classId, pro, sexId, displayId, id, countArr, total, target}) {
      let index, i;
      index = state.recommendHomeData.findIndex(obj => {
        if(obj.classId === classId && obj.sexId === sexId && obj.displayId === displayId) {
          i = obj[target].arr.findIndex(n => n.pro === pro && n.styId === id);
          return true;
        }else return false
      })
      if(index === -1 || i === -1) return;
      if(countArr) state.recommendHomeData[index][target].arr[i].skuData.data = countArr;
      state.recommendHomeData[index][target].arr[i].count = total;
    },
    /* 筛选首页数据 */
    filterHomeData (state, data) {
      let keys = Object.keys(data);
      state.recommendHomeData = state.recommendHomeData.map(obj => {
        //循环款
        let leftArr = obj.leftLists.arr.map(detail => {
          let status = keys.every(/* 存在该筛选字段 */filter => {
            // 款号过滤
            if(filter === 'querySearch') return detail.pro.includes(data[filter]);
            // 满足价格条件
            else if(filter === 'price') return (isInvalid(data[filter][0]) || detail.price >= data[filter][0]) && (isInvalid(data[filter][1]) || detail.price <= data[filter][1]);
            // 满足筛选的条件的数量小于自身所拥有条件的数量并且所筛选的条件存在于自身所拥有条件中
            else if(data[filter].length){
              return /*data[filter].length <= detail[filter].length && */detail[filter].some(id => {
                return data[filter].includes(id); // 只要符合条件
              })
            }else return true
          });
          return {
            ...detail,
            isShow: status
          }
        })
        let rightArr = obj.rightLists.arr.map(detail => {
          let status = keys.every(/* 存在该筛选字段 */filter => {
            // 款号过滤
            if(filter === 'querySearch') return detail.pro.includes(data[filter]);
            // 满足价格条件
            else if(filter === 'price') return (isInvalid(data[filter][0]) || detail.price >= data[filter][0]) && (isInvalid(data[filter][1]) || detail.price <= data[filter][1]);
            // 满足筛选的条件的数量小于自身所拥有条件的数量并且所筛选的条件存在于自身所拥有条件中
            else if(data[filter].length){
              return /*data[filter].length <= detail[filter].length && */detail[filter].some(id => {
                return data[filter].includes(id); // 只要符合条件
              })
            }else return true
          });
          return {
            ...detail,
            isShow: status
          }
        })
        return {
          ...obj,
          isShow: leftArr.some(n => n.isShow) || rightArr.some(n => n.isShow),
          leftLists: {
            checked: obj.leftLists.checked,
            disabled: obj.leftLists.disabled,
            arr: leftArr
          },
          rightLists: {
            checked: obj.rightLists.checked,
            disabled: obj.rightLists.disabled,
            arr: rightArr
          }
        }
      })
    }
  },
  getters: {
    /* 首页是否全选 */
    homeChecked (state) {
      let total = 0, selectedTotal = 0;
      state.recommendHomeData.map(obj => {
        obj.leftLists.arr.map(n => {
          // 退仓款并且未禁用
          if(n.isReturnWarehouse && !n.disabled) {
            ++total;
            if(n.checked) ++selectedTotal;
          }
        })
        obj.rightLists.arr.map(n => {
          if(!n.disabled) {
            ++total;
            if(n.checked) ++selectedTotal;
          }
        })
      })
      return total !== 0 && selectedTotal === total;
    },
    /* 首页退仓款总件数 */
    homeLeftCount (state) {
      return state.recommendHomeData.reduce((total, obj) => {
        let objCount = obj.leftLists.arr.reduce((count, n) => {
          if(n.isReturnWarehouse && !n.disabled && n.checked) {
            count += n.count;
          }
          return count
        }, 0);
        return total + objCount
      }, 0)
    },
    /* 首页退仓款数 */
    homeLeftStyle (state) {
      return state.recommendHomeData.reduce((total, obj) => {
        let objCount = obj.leftLists.arr.reduce((count, n) => {
          if(n.isReturnWarehouse && !n.disabled && n.checked) {
            ++count;
          }
          return count
        }, 0);
        return total + objCount
      }, 0)
    },
    /* 首页可选款总件数 */
    homeRightCount (state) {
      return state.recommendHomeData.reduce((total, obj) => {
        let objCount = obj.rightLists.arr.reduce((count, n) => {
          if(!n.disabled && n.checked) {
            count += n.count;
          }
          return count
        }, 0);
        return total + objCount
      }, 0)
    },
    /* 首页可选款数 */
    homeRightStyle (state) {
      return state.recommendHomeData.reduce((total, obj) => {
        let objCount = obj.rightLists.arr.reduce((count, n) => {
          if(!n.disabled && n.checked) {
            ++count;
          }
          return count
        }, 0);
        return total + objCount
      }, 0)
    },
  },
  actions: {
    /* 获取首页列表数据 */
    getRecommendHomeData ({ commit, state }, cb) {
      function compare (a, b, arr) {
        for(let i = 0; i < arr.length; i++) {
          if(a[arr[i].name] !== b[arr[i].name]) return arr[i].des? b[arr[i].name] - a[arr[i].name] : a[arr[i].name] - b[arr[i].name]
        }
      }
      $http({
        url: '/api/SelPro/GetItemsV',
        method: 'post',
        data: {
          strId: state.userId
        }
      }).then(res => {
        let data = res.data;
        if(data.code === 1) {
          let arr = data.data || [];
          let group = {};
          let natureClassObj = {
            0: 'nature-unsold', // 滞销
            1: 'nature-matters', // 平销
            2: 'nature-best', // 畅销
            3: 'nature-hot' // 爆卖
          };
          arr.map(obj => {
            let mapKey = `${obj.styleClassCode}${obj.styleSexId}${obj.displayLocationCode}`;
            if(!group[mapKey]) {
              group[mapKey] = {
                identifier: Math.round(Math.random() * 1000000000),
                isShow: true, // 是否显示
                canSelCnt: obj.canSelCnt,//可添加款
                distribCode: obj.promotionTypeName,//配销中心编码
                distribId: obj.distribId,//配销中心编码
                distribName: obj.distribName,//配销中心编码
                display: obj.displayLocationName, // 陈列位置
                displayId: obj.displayLocationId, // 陈列位置id
                strCode: obj.strCode,//门店编码
                strId: obj.strId,//门店id
                class: obj.styleClassName,//大类
                classId: obj.styleClassId,//大类id
                classCode: obj.styleClassCode,//大类code
                sex: obj.styleSexName,//性别
                sexId: obj.styleSexId,//性别Id
                sexCode: obj.styleSexCode,//性别编码
                sexSort: obj.styleSexCode == '1'? 3 : (obj.styleSexCode == '2'? 2 : 0),//用于性别排序
                warehouse: obj.canBakCnt || 0, // 退仓款数
                now: obj.styCntIn || 0, // 现有款数
                sporadic: 0,
                choosable: obj.styCntSelActual >= 0? obj.styCntSelActual : 0,// 显示的可补充款数
                realChoose: obj.styCntSelActual || 0, // 真实的可补充款数
                targetCount: obj.styCntTarget || 0, // 目标款
                //canToChoose: obj.canSelCnt || 0,//可供选款数
                leftLists: {
                  arr: [],
                  checked: false,
                  disabled: false
                }, // 左边款集合
                rightLists: {
                  arr: [],
                  checked: false,
                  disabled: false
                }, // 右边款集合
              }
            }
            let classObj = group[mapKey];
            let displayArr = (obj.selPeoStyMsgs || []).map(detail => {
              let imgList = detail.imgClr === ''? [] : JSON.parse(detail.imgClr);
              let skuList = detail.skuLists;
              let skuData = dealColorSize(imgList, skuList);
              let images = (detail.img? JSON.parse(detail.img) : []).map(n => ({
                src: n.URL
              }));
              return {
                isShow: true,//根据筛选控制是否显示
                disabled: false,//是否禁用
                checked: false,
                styType: obj.styType, // 类型(1: 零星款 2: 可选款)
                /*--------以下用于搜索需要--------*/
                sty_clr: detail.clrIds? detail.clrIds.split(',') : [],//颜色id集合
                sty_size: detail.sizeIds? detail.sizeIds.split(',') : [],//尺寸id集合
                sty_season: [detail.seasonId],//季节id
                sty_year: [detail.yearId],//年份id
                sty_sex: [obj.styleSexId], // 性别id
                sty_clear: [detail.styClearId], // 清理款标识id
                sty_display_location: [detail.displayLocationId], // 陈列位置id
                /*--------------------*/
                sortId: Math.floor(Math.random() * 100), // 右边排序标识符
                styClearCode: detail.styClearCode, // 清理款code
                styClearId: detail.styClearId, // 清理款id
                styClearName: detail.styClearName, // 清理款标识
                sporadicCode: detail.isLil, // 零星款标识
                sex: obj.styleSexName,//性别
                sexId: obj.styleSexId,//性别Id
                sexCode: obj.styleSexCode,//性别编码
                sexSort: obj.styleSexCode == '1'? 3 : (obj.styleSexCode == '2'? 2 : 0),//用于性别排序
                pro: detail.styCode,//商品编码
                name: detail.styName,//商品名称
                styId: detail.styId,//商品id
                natureName: detail.salNatureName, // 销售性质名称
                natureCode: detail.salNature, // 销售性质编码
                natureClass: natureClassObj[detail.salNature], // 销售性质样式
                // styClearCode: 1 (清理款) isLil: 1(零星款)
                clearClass: detail.isNewSty? 'nature-new' : detail.styClearCode == 1? 'nature-clear' : detail.isLil == 1? 'nature-zero' : '',
                clearName: detail.isNewSty? '新' : (detail.styClearCode == 1? '清' : detail.isLil == 1? '零' : ''),
                isSporadic: detail.isLil == 1, // 是否为零星款
                isReturnWarehouse: detail.isCanBak == 1, // 是否为退仓款
                isClear: detail.styClearCode == 1, // 是否为清理款
                currentId: detail.isExtSty, // 现有款标识符  1或0
                displayId: detail.displayLocationId,//陈列位置id,
                tag: detail.displayLocationName,//促销标签(陈列位置)
                tagId: detail.displayLocationId,//促销标签(陈列位置)id
                tagCode: detail.displayLocationCode,//促销标签(陈列位置)code
                seasonName: detail.seasonName,//季节名称
                seasonId: detail.seasonId,//季节id
                seasonCode: detail.seasonCode,//季节编码
                retailAmt7d: detail.retailAmt7d || 0, // 周销售金额
                sales: `周销量${detail.qtyRetail7d || 0}`,//周销量
                weekAverage: `周日均${detail.qtyAvg7d || 0}`,//周日均
                reason: detail.itmSuggestReasonName,//推荐理由
                itmSuggestReasonRank: detail.itmSuggestReasonRank,//推荐排名
                clothesLength: detail.lenName,//衣长
                outsideSleeve: detail.slveLenName,//袖长
                FAB: detail.styFab,//FAB
                dropPrice: (detail.stdPrice || 0)/*.toFixed(2)*/,//吊牌价
                retailPrice: detail.retailPrice,//零售价
                price: (detail.retailPrice || detail.stdPrice || 0)/*.toFixed(2)*/,//最终显示价格
                count: detail.qtySelPro || 0,//可修改的数量
                oldCount: detail.qtySelPro || 0,//原数量
                yearName: detail.yearName,//年份
                yearId: detail.yearId,//年份Id
                yearCode: detail.yearCode,//年份code
                countChange: false,//修改数量弹出框控制
                collect: detail.isAtten === 1,//是否收藏了
                label: detail.isTopDistrib === 1? '分区50大' : (detail.isTopClass === 1? '品类前3' : detail.isTopPlan === 1? '计划50大' : ''), // 前50大标签
                skuData,
                images, // sku图片集合
              }
            });
            classObj[obj.styType == 1? 'leftLists' : 'rightLists'].arr.push(...displayArr);
            Object.assign(classObj,obj.styType == 1? {
              warehouse: obj.canBakCnt || 0, // 退仓款数
              now: obj.styCntIn || 0, // 现有款数
              sporadic: (classObj.sporadic || 0) + displayArr.filter(n => n.isSporadic && n.styType == 1).length, // 零星款数
              targetCount: obj.styCntTarget || 0, // 目标款
            }: {}, {
              choosable: obj.styCntSelActual >= 0? obj.styCntSelActual : 0,// 显示的可补充款数
              realChoose: obj.styCntSelActual || 0, // 真实的可补充款数
            })
          })
          let lists = Object.keys(group).sort().map(key => ({
            ...group[key],
            // 左边列表数据
            leftLists: {
              checked: false,
              disabled: group[key].leftLists.arr.filter(n => n.isReturnWarehouse).length === 0,
              arr: group[key].leftLists.arr.map(n => ({
                ...n,
                disabled: !n.isReturnWarehouse
              })).sort((a, b) => {
                return compare(a, b, [...state.sortHomeList])
              })
            },
            rightLists: {
              // 清理款数量为0并且实际可选款小于等于0禁用
              disabled: group[key].rightLists.arr.filter(n => n.isClear).length === 0 && group[key].realChoose <= 0,
              checked: false,
              arr: group[key].rightLists.arr.sort((a, b) => {
                return compare(a, b, [...state.sortHomeList])
              }).map(n => ({
                ...n,
                disabled: !n.isClear && group[key].realChoose <= 0 // 非清理款并且可选款数小于等于0禁用
              }))
            }
          })).filter(n => n.leftLists.arr.length || n.rightLists.arr.length);
          commit('setHomeRecommendData', lists);
        }
      })
    }
  }
})
